﻿using AbpApplication.Expand;
using AbpApplication.InPut;
using AbpEntityFrameworkcore.DbContext;
using AbpToDomain.EntityInfo;
using Application.Expand;
using LinqSharp;
using Microsoft.Extensions.Logging;
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace AbpApplication.AppServices
{
    public class BaseService : ApplicationService, IBaseService
    {

        private readonly IRepository<Box> Box_res;
        private readonly IRepository<BoxGrid> BoxGrid_res;
        private readonly IRepository<BoxPosition> BoxPosition_res;
        private readonly IRepository<Warehouse> Warehouse_res;
        private readonly IRepository<WarehouseLine> WarehouseLine_res;
        private readonly IRepository<MaterialBase> MaterialBase_res;
        private readonly MyDbContext context;
        private readonly QueryDynamic_WarehouseLine queryDynamic_WarehouseLine;
        private readonly QueryDynamic_Box queryDynamic_Box;




        public BaseService(
            IRepository<Box> box_res,
            IRepository<BoxGrid> boxGrid_res,
            IRepository<BoxPosition> boxPosition_res,
            IRepository<Warehouse> warehouse_res,
            IRepository<WarehouseLine> warehouseLine_res,
            IRepository<MaterialBase> materialBase_res,
            MyDbContext context,
            QueryDynamic_WarehouseLine queryDynamic_WarehouseLine,
            QueryDynamic_Box queryDynamic_Box)
        {
            Box_res = box_res;
            BoxGrid_res = boxGrid_res;
            BoxPosition_res = boxPosition_res;
            Warehouse_res = warehouse_res;
            WarehouseLine_res = warehouseLine_res;
            MaterialBase_res = materialBase_res;
            this.context = context;
            this.queryDynamic_WarehouseLine = queryDynamic_WarehouseLine;
            this.queryDynamic_Box = queryDynamic_Box;
        }

        public async Task<ApiResponse> Create_Boxs(InPut_BaseService input)//配置箱盒
        {
            try
            {
   


                bool res = await Box_res.AnyAsync(x => x.BoxCode.Substring(x.BoxCode.Length - 4) == input.StartNumber.ToString("D4") || x.BoxCode.Substring(x.BoxCode.Length - 4) == input.EndNumber.ToString("D4"));
                if (res)
                {
                    return new ApiResponse("箱盒已存在", false, null);
                }
                //配置箱盒
                int boxquantity = input.EndNumber - input.StartNumber + 1;
                List<Box> boxes = new List<Box>();
                for (int i = 0; i < boxquantity; i++)//箱
                {
                    Box box = new Box();
                    string BoxCode = "A" + "0000" + (input.StartNumber + i).ToString("D4");
                    box = box.AddBox(BoxCode, input.BoxGridQuantity);
                    List<BoxGrid> boxGrids = new List<BoxGrid>();
                    for (int y = 0; y < input.BoxGridQuantity; y++)//格
                    {
                        BoxGrid boxGrid = new BoxGrid();
                        string BoxGridCode = $"{BoxCode}_{(y + 1).ToString("D2")}";
                        boxGrid = boxGrid.AddBoxGrid(y + 1, BoxGridCode, input.BoxPositionQuantity, box);
                        List<BoxPosition> boxPositions = new List<BoxPosition>();
                        for (int x = 0; x < input.BoxPositionQuantity; x++)//位
                        {
                            BoxPosition boxPosition = new BoxPosition();
                            string BoxPositionCode = BoxGridCode + "_" + (x + 1).ToString("D2");
                            boxPosition = boxPosition.AddBoxPosition(x + 1, BoxPositionCode, boxGrid);
                         
                            boxPositions.Add(boxPosition);
                        }
                        await BoxPosition_res.InsertManyAsync(boxPositions);
                        boxGrid.BoxPositions.AddRange(boxPositions);
                        boxGrids.Add(boxGrid);
                    }
                    await BoxGrid_res.InsertManyAsync(boxGrids);
                    box.BoxGrids.AddRange(boxGrids);
                    boxes.Add(box);
                }
                await Box_res.InsertManyAsync(boxes);
                return new ApiResponse("生成成功", true, null);
            }
            catch(Exception ex)
            {
                Logger.LogWarning($"Create_Boxs-{input}"+ ex.Message);
                return new ApiResponse("内部服务器错误", false,null);
            }

         
        }

        public async Task<ApiResponse> Create_Warehouses(InPut_BaseService3 input)//配置库位
        {
            try
            {
                bool res= await Warehouse_res.AnyAsync(x=>x.WarehouseCode == input.WarehouseCode);
                if (res)
                {
                    return new ApiResponse("库位名称重复", false, null);
                }
                Warehouse warehouse = new Warehouse();
                warehouse = warehouse.AddWarehouse(input.WarehouseCode, input.Xaxis, input.Yaxis, input.Zaxis);
                await Warehouse_res.InsertAsync(warehouse);
                int sum = input.Xaxis * input.Yaxis * input.Zaxis;
                List<WarehouseLine> lines = new List<WarehouseLine>();
            
                    //排
                    for (int j = 1; j <= input.Xaxis; j++)
                    {
                        //高
                        for (int k = 1; k <= input.Yaxis; k++)
                        {
                            //列
                            for (int y = 1; y <= input.Zaxis; y++)
                            {
                                WarehouseLine warehouseLine = new WarehouseLine();
                                warehouseLine = warehouseLine.AddWarehouseline(input.Long, input.Wide,input.high, j, k, y, warehouse);
                                warehouseLine.WarehouseLineCode = warehouse.WarehouseCode + "-" + j.ToString("D2") + "-" + k.ToString("D2") + "-" + y.ToString("D2");
                                lines.Add(warehouseLine);
                            }
                        }
                    }
               
                warehouse.warehouselines.AddRange(lines);
                await Warehouse_res.InsertAsync(warehouse);
                await WarehouseLine_res.InsertManyAsync(lines);
                return new ApiResponse("配置成功", true, null);
            }
            catch (Exception ex)
            {
                Logger.LogWarning($"Create_Warehouses-{input}"+ex.Message);
                return new ApiResponse("内部错误服务器", false,null);
            }

        }

        public async Task<ApiResponse> Update_Box(InPut_BaseService2 input)//更改箱盒
        {
            try
            {

                var boxs = await Box_res.WithDetailsAsync();
                foreach (var boxcode in input.BoxCode)
                {
                    Box box = boxs.FirstOrDefault(x => x.BoxCode == boxcode);
                    if (box == null)
                    {
                        return new ApiResponse("未查询到", false, null);
                    }
                    box.BoxGrids .Clear();
                    await Box_res.UpdateAsync(box);
                    await UnitOfWorkManager.Current.SaveChangesAsync();

                    List<BoxGrid> boxGrids = new List<BoxGrid>();
                    for (int i = 0; i < input.BoxGridQuantity; i++)
                    {
                        BoxGrid boxGrid = new BoxGrid();
                        string BoxGridCode = $"{box.BoxCode}_{(i + 1).ToString("D2")}";
                        boxGrid = boxGrid.AddBoxGrid(i + 1, BoxGridCode, (int)input.BoxPositionQuantity, box);
                        List<BoxPosition> boxPositions = new List<BoxPosition>();
                        for (int j = 0; j < input.BoxPositionQuantity; j++)
                        {
                            BoxPosition boxPosition = new BoxPosition();
                            string BoxPositionCode = BoxGridCode + "_" + (j + 1).ToString("D2");
                            boxPosition = boxPosition.AddBoxPosition(j + 1, BoxPositionCode, boxGrid);
                            boxPositions.Add(boxPosition);
                        }
                        boxGrid.BoxPositions.Clear();
                        boxGrid.BoxPositions.AddRange(boxPositions);
                        boxGrid.BoxPositionQuantity = (int)input.BoxPositionQuantity;
                        boxGrids.Add(boxGrid);

                    }
                    await BoxGrid_res.InsertManyAsync(boxGrids);
                    box.BoxGrids.Clear();
                    box.BoxGrids.AddRange(boxGrids);
                    box.BoxGridQuantity = (int)input.BoxGridQuantity;
                    await Box_res.UpdateAsync(box);

                }
                return new ApiResponse("更新成功", true, null);

            }
           catch (Exception ex)
            {
                Logger.LogWarning($"Update_Box-{input}" + ex.Message);
                return new ApiResponse("内部服务器错误", false,null);
            }


        }
       
        public async Task<ApiResponsePage> GetList_WarehouseLine(InPut_BaseService4 inPut)  //获取仓位列表  
        {

            try
            {
                var warehouseLines = queryDynamic_WarehouseLine.QueryDynameic(inPut.WarehouseCode, inPut.Long, inPut.Wide, inPut.high, inPut.Xaxis, inPut.Yaxis, inPut.Zaxis, inPut.IsEnable);
                long count = warehouseLines.LongCount();//计算出了总条数
                long pageCount = (long)Math.Ceiling(count * 1.0 / inPut.PageSize);
                warehouseLines = warehouseLines.SelectPage(inPut.PageIndex, inPut.PageSize).ToList();
                return new ApiResponsePage("获取成功", true, warehouseLines, count, pageCount);
            }
            catch (Exception ex)
            {
                Logger.LogWarning($"GetList_WarehouseLine-{inPut}" + ex.Message);
                return new ApiResponsePage("内部服务器错误", false, null,null,null);
            }


        }

        public  void test()
        {
            Logger.LogWarning("你好");
        
        }

        public async Task<ApiResponse> Update_WarehouseLines(InPut_BaseService5 inPut)//更新仓位状态
        {
            try
            {
                foreach (var item in inPut.WarehouseLineCodes)
                {
                    WarehouseLine warehouseLine = await WarehouseLine_res.FirstOrDefaultAsync(x => x.WarehouseLineCode == item);
                    if (warehouseLine != null)
                    {
                        warehouseLine.IsEnable = inPut.Type;
                    }
                    await WarehouseLine_res.UpdateAsync(warehouseLine);
                }
                return new ApiResponse("修改成功", true, null);

            }
            catch(Exception ex)
            {
                Logger.LogWarning($"Update_WarehouseLines{inPut}" + ex.Message);
                return new ApiResponse("内部服务器错误", false, null);
            }



        }

        public async Task<ApiResponsePage> GetList_Boxs(InPut_BaseService6 inPut)
        {
            try
            {
                var boxs = queryDynamic_Box.QueryDynameic(inPut.BoxCode);
                long count = boxs.LongCount();//计算出了总条数
                long pageCount = (long)Math.Ceiling(count * 1.0 / inPut.PageSize);
                boxs = boxs.SelectPage(inPut.PageIndex, inPut.PageSize).ToList();
                return new ApiResponsePage("获取成功", true, boxs, count, pageCount);
            }
            catch (Exception ex)
            {
                Logger.LogWarning($"GetList_WarehouseLine-{inPut}" + ex.Message);
                return new ApiResponsePage("内部服务器错误", false, null, null, null);
            }

        }

    
    }
}
